# -*- coding: utf-8 -*-
import json
import time
from datetime import datetime

import requests
from django.conf import settings

from common.bankcard.model import BANK_DCT
from common.mch.db import get_account
from common.recharge.model import RECHARGE_ORDER_STATUS
from common.utils import track_logging

_LOGGER = track_logging.getLogger('third')

BANKCARD_NOT_ACQUIRE = -1


def _get_pay_type(type):
    if type == 'alipay':
        return 'Alipay2Bank'
    elif type == 'wechat':
        return 'WX2Bank'
    else:
        return None


def tonglue_create_order(order, bankcard):
    try:
        mch = get_account(order.mch_id)
        mch_name = mch.name if mch.name != u'泰坦' else 'TT'
        post_data = {
            "apikey": settings.THIRD_API_KEY,
            "order_id": '_'.join([mch_name, str(order.id)]),
            "bank_flag": BANK_DCT[bankcard.bank],
            "card_login_name": bankcard.account_holder,
            "card_number": str(order.receive_card_num),
            "pay_card_number": order.pay_account_num,
            "pay_username": order.pay_account_username,
            "amount": order.amount,
            "create_time": int(time.mktime(order.created_at.timetuple())),
            "comment": "",
        }
        # if order.pay_type in ['alipay', 'wechat']:
        #     post_data['meta_data'] = {'QuickOrder': _get_pay_type(order.pay_type)}
        j = json.dumps(post_data)
        _LOGGER.info('tonglue create: %s', j)
        response = requests.post(settings.THIRD_URL + 'authority/system/api/place_order/',
                                 headers={'Content-type': 'application/json', 'Accept': 'text/plain'},
                                 data=j, timeout=5)
        _LOGGER.info('tonglue order_id: %s, resp: %s %s', order.id, response.status_code, response.content)
        response = json.loads(response.content)
        success = response.get('success', None)
        third_id = response.get('id', None)
        if success and third_id:
            order.status = RECHARGE_ORDER_STATUS.THIRD
            order.third_id = str(third_id)
            order.updated_at = datetime.utcnow()
            order.save()
            return True
        else:
            return False
    except Exception, e:
        _LOGGER.info('tonglue create order fail: %s' % e)
        return False


def tonglue_revoke_order(third_id):
    try:
        post_data = {
            "apikey": settings.THIRD_API_KEY,
            "id": int(third_id),
        }
        j = json.dumps(post_data)
        url = settings.THIRD_URL + 'authority/system/api/revoke_order/'
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        _LOGGER.info('tonglue_revoke_order: %s', j)
        response = requests.post(url, headers=headers, data=j, timeout=5)
        _LOGGER.info('tonglue_revoke_order resp: %s %s', response.status_code, response.content)
    except Exception, e:
        _LOGGER.info('tonglue_revoke_order fail: %s' % e)
